import { apiData, param2Obj, getRandom } from '@/utils'
import LocalStorage from 'localStorage'
import Mock from 'mockjs'

const listKey = 'node_getModuleList'
var listData = JSON.parse(LocalStorage.getItem(listKey))

if (listData === null || !listData) {
  const num = getRandom(15, 30)
  listData = []
  for (var i = 0; i <= num; i++) {
    listData.push(Mock.mock({
      id: '@increment',
      module_title: '@cname',
      modulename: '@name',
      sort: '@increment',
      'type|0-2': 0,
      'install|0-1': 0
    }))
  }

  // 保存数据
  LocalStorage.setItem(listKey, JSON.stringify(listData))
}

export default {
  getModuleList: config => {
    const { type = 0 } = param2Obj(config.url)
    let mockDatas = JSON.parse(LocalStorage.getItem(listKey)) || []
    mockDatas = mockDatas.filter(item => {
      return item.type - type === 0 || (item.type === 1 && item.install === 1)
    })
    return apiData('', '获取模块列表', mockDatas)
  },
  nodeDel: config => {
    const { id } = param2Obj(config.url)
    if (id <= 0) {
      return apiData(3001, '数据ID不能为空')
    }

    // 获取数据
    const allData = JSON.parse(LocalStorage.getItem(listKey))
    const dVal = []
    for (var i = allData.length - 1; i >= 0; i--) {
      if (!(allData[i] !== null && allData[i]['id'] === id)) {
        dVal.push(allData[i])
      }
    }
    // 保存数据
    LocalStorage.setItem(listKey, JSON.stringify(dVal))

    return apiData('', '删除成功！')
  },
  nodeAdd: config => {
    return apiData('', '成功', config)
  }
}
